package com.tebiecloud.order.server.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tebiecloud.act.client.model.entity.Act;
import com.tebiecloud.base.client.constants.BaseConstants;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.model.PageParams;
import com.tebiecloud.common.security.SecurityHelper;
import com.tebiecloud.common.security.SecurityUserDetails;
import com.tebiecloud.common.utils.JsonUtils;
import com.tebiecloud.common.utils.RedisUtils;
import com.tebiecloud.order.client.constatns.OrderConstants;
import com.tebiecloud.order.client.model.entity.OrderGoods;
import com.tebiecloud.order.client.model.entity.Orderr;
import com.tebiecloud.order.client.model.entity.OrderRefund;
import com.tebiecloud.order.server.service.*;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.ResultBodyUtils;
import com.tebiecloud.order.server.service.feign.*;
import com.tebiecloud.retail.client.constants.RetailConstants;
import com.tebiecloud.yunst.client.model.vo.RefundVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;

import java.awt.*;
import java.util.List;
import java.util.Map;

/**
 * 订单退款信息 前端控制器
 * @author tebie
 * @date 2019-09-17
 */
@Slf4j
@RestController
@RequestMapping("/orderrefund")
public class OrderRefundController {

    @Autowired
    private OrderRefundService orderRefundService;

    @Autowired
    private OrderrService orderService;

    @Autowired
    private OrderStats1Service orderStats1Service;

    @Autowired
    private ActServiceClient actServiceClient;

    @Autowired
    private OrderGoodsService orderGoodsService;

    @Autowired
    private RetailOrderServiceClient retailOrderServiceClient;

    @Autowired
    private YunRefundServiceClient yunRefundServiceClient;

    @Autowired
    private MpweixinServiceClient mpweixinServiceClient;

    /**
     * 提交退款接口
     * @param orderId 订单id,
     * @param reason 退货退款原因,
     * @param remark 退货退款说明
     * @return
     */
    @PostMapping("add")
    public ResultBody add(
            @RequestParam(value = "orderId") Long orderId,
            @RequestParam(value = "reason", required = false) String reason,
            @RequestParam(value = "remark", required = false) String remark
    ) {
        // 获取当前用户信息
        SecurityUserDetails securityUserDetails = SecurityHelper.getUser();
        long userId = securityUserDetails.getUserId().longValue();

        // 获取订单信息
        Orderr order = orderService.getById(orderId);
        if(order == null) {
            log.error("xiaoc>> 申请退款，获取订单信息失败，orderId: {}", orderId);
            return ResultBodyUtils.failed("订单不存在");
        }
        if(BaseConstants.ACCOUNT_TYPE_MP.equalsIgnoreCase(securityUserDetails.getAccountType())) { // 公众号登录判断
            if(order.getUserId().longValue() != userId) {
                log.error("xiaoc>> 申请退款，无权限操作，current userId: {}, order: {}", userId, JsonUtils.Obj2Str(order));
                return ResultBodyUtils.failed("无权限执行该执行该操作");
            }
        }
        if(order.getStatus() != 2) {
            log.error("xiaoc>> 申请退款，获取订单信息失败，orderId: {}", orderId);
            return ResultBodyUtils.failed("当前订单状态不允许退款");
        }
        //检查活动是否可退
        if(order.getActId()!=null){
            ResultBody<Act> refact = actServiceClient.selectActByActId(order.getActId());
            if(refact!=null && refact.getCode() == ResultEnum.OK.getCode()){
                Act act = refact.getData();
                if(act != null){
                    if(act.getIsRefundable().equals(0) || act.getActType().equals(2)){
                        return ResultBodyUtils.failed("当前订单所属活动不允许退款");
                    }
                }
            }
        }
        //校验是否全部余额支付
        if(order.getPayReady()>0){
            //退回实际支付金额
            ResultBody<RefundVO> retRefundVO = yunRefundServiceClient.create(userId, orderId, order.getPayReady());
            if(retRefundVO.getCode() != ResultEnum.OK.getCode()) {
                log.error("xioac>> 订单退款，退回实际支付金额有误，retRefund: {}", JsonUtils.Obj2Str(retRefundVO));
                return ResultBodyUtils.failed(retRefundVO.getMsg());
            }
        }
        // 更新订单状态
        Orderr orderUpdate = new Orderr();
        orderUpdate.setOrderId(orderId);
        orderUpdate.setStatus(6);
        orderService.updateById(orderUpdate);

        //查询权益
        QueryWrapper<OrderGoods> orderGoodsQueryWrapper = new QueryWrapper<>();
        orderGoodsQueryWrapper.eq("order_id",order.getOrderId());
        List<OrderGoods> orderGoodsList = orderGoodsService.list(orderGoodsQueryWrapper);
        if(orderGoodsList!=null && orderGoodsList.size()>0){
            //去除权益
            for(OrderGoods orderGoods:orderGoodsList){
                UpdateWrapper<OrderGoods> orderGoodsUpdateWrapper = new UpdateWrapper<>();
                orderGoodsUpdateWrapper.eq("order_goods_id",orderGoods.getOrderGoodsId());
                OrderGoods orderGoods1 = new OrderGoods();
                orderGoods1.setRemainWriteOffTimes(0);
                orderGoodsService.update(orderGoods1,orderGoodsUpdateWrapper);
            }
        }

        // 添加退款信息
        OrderRefund entity = new OrderRefund();
        entity.setOrderId(orderId);
        entity.setReason(reason);
        entity.setExplainn(remark);
        entity.setReceiver(order.getReceiver());
        entity.setPhone(order.getPhone());
        if(BaseConstants.ACCOUNT_TYPE_MP.equalsIgnoreCase(securityUserDetails.getAccountType())) {
            entity.setType(1); // 1用户发起退款
        } else if(BaseConstants.ACCOUNT_TYPE_MINIPROGRAM.equalsIgnoreCase(securityUserDetails.getAccountType())){
            entity.setType(2); // 2商户发起退款
        } else {
            entity.setType(0); // 未知
        }
        entity.setInHand(0);//未收货
        entity.setStatus(4);//已退款
        orderRefundService.save(entity);

        // 更新订单分销信息
        ResultBody retUpdateRetailOrder = retailOrderServiceClient.updateRetailOrder(orderId, RetailConstants.RETAIL_ORDER_REFUND); // 6已退款
        if(retUpdateRetailOrder.getCode() != ResultEnum.OK.getCode()) {
            log.error("xioac>> 订单退款，更新分销订单信息有误，retUpdateRetailOrder: {}", JsonUtils.Obj2Str(retUpdateRetailOrder));
        }
        // 退回美乖乖币与余额
        int balance = order.getPayBalances()==null?0:order.getPayBalances();
        int coin = order.getPayMgg()==null?0:order.getPayMgg();
        if(order.getPayBalances()>0 || order.getPayMgg()>0){
            ResultBody retUpdatePlusAmount = mpweixinServiceClient.callBackPlusAmount(order.getOrderId(),userId,balance,coin,6);
            if(retUpdatePlusAmount.getCode() != ResultEnum.OK.getCode()) {
                log.error("xioac>> 订单退款，退回美乖乖币与余额有误，retUpdatePlusAmount: {}", JsonUtils.Obj2Str(retUpdatePlusAmount));
            }
        }
        //修改会员权益
        orderStats1Service.createOrUpdate(null,userId,order.getStoreId(),null,null,null,0,-order.getPrice());
        return ResultBodyUtils.ok();
    }






//    /**
//     * 获取分页数据
//     * @param map
//     * @return
//     */
//    @GetMapping(value = "list")
//    public ResultBody<IPage<OrderRefund>> list(@RequestParam(required = false) Map map) {
//        PageParams pageParams = new PageParams(map);
//        OrderRefund query = pageParams.mapToObject(OrderRefund.class);
//        QueryWrapper<OrderRefund> queryWrapper = new QueryWrapper();
//        return ResultBodyUtils.ok(orderRefundService.page(new PageParams(map), queryWrapper));
//    }
//
//    /**
//     * 根据ID查找数据
//     * @param id
//     * @return
//     */
//    @GetMapping("get")
//    public ResultBody<OrderRefund> get(@RequestParam("id") Long id) {
//        OrderRefund entity = orderRefundService.getById(id);
//        return ResultBodyUtils.ok(entity);
//    }
//
//    /**
//     * 添加数据
//     * @param orderId 订单id,
//     * @param type 退款类型：1用户发起退款，2商户发起退款,
//     * @param inHand 收货状态，0未收货1已收货,
//     * @param reason 退货退款原因,
//     * @param status 状态，0没有退成功1退款审核中2等待退货3退货中4已退货退款,
//     * @param explainn 退货退款说明,
//     * @param receiver 收货人名称,
//     * @param address 收货地址,
//     * @param phone 收货人联系号码,
//     * @param logistics 物流公司,
//     * @param courierNumber 快递单号,
//     * @param senderPhone 寄出人联系号码,
//     * @param refuseReason 申请退货退款失败原因
//     * @return
//     */
//    @PostMapping("add")
//    public ResultBody add(
//        @RequestParam(value = "orderId", required = false) Integer orderId,
//        @RequestParam(value = "type", required = false) Integer type,
//        @RequestParam(value = "inHand", required = false) Integer inHand,
//        @RequestParam(value = "reason", required = false) String reason,
//        @RequestParam(value = "status", required = false) Integer status,
//        @RequestParam(value = "explainn", required = false) String explainn,
//        @RequestParam(value = "receiver", required = false) String receiver,
//        @RequestParam(value = "address", required = false) String address,
//        @RequestParam(value = "phone", required = false) String phone,
//        @RequestParam(value = "logistics", required = false) String logistics,
//        @RequestParam(value = "courierNumber", required = false) String courierNumber,
//        @RequestParam(value = "senderPhone", required = false) String senderPhone,
//        @RequestParam(value = "refuseReason", required = false) String refuseReason
//    ) {
//        OrderRefund entity = new OrderRefund();
//        entity.setOrderId(orderId);
//        entity.setType(type);
//        entity.setInHand(inHand);
//        entity.setReason(reason);
//        entity.setStatus(status);
//        entity.setExplainn(explainn);
//        entity.setReceiver(receiver);
//        entity.setAddress(address);
//        entity.setPhone(phone);
//        entity.setLogistics(logistics);
//        entity.setCourierNumber(courierNumber);
//        entity.setSenderPhone(senderPhone);
//        entity.setRefuseReason(refuseReason);
//        orderRefundService.save(entity);
//        return ResultBodyUtils.ok();
//    }
//
//    /**
//     * 更新数据
//     * @param orderId 订单id
//     * @param type 退款类型：1用户发起退款，2商户发起退款
//     * @param inHand 收货状态，0未收货1已收货
//     * @param reason 退货退款原因
//     * @param status 状态，0没有退成功1退款审核中2等待退货3退货中4已退货退款
//     * @param explainn 退货退款说明
//     * @param receiver 收货人名称
//     * @param address 收货地址
//     * @param phone 收货人联系号码
//     * @param logistics 物流公司
//     * @param courierNumber 快递单号
//     * @param senderPhone 寄出人联系号码
//     * @param refuseReason 申请退货退款失败原因
//     * @return
//     */
//    @PostMapping("update")
//    public ResultBody update(
//            @RequestParam(value = "orderRefundId", required = false) Long orderRefundId,
//            @RequestParam(value = "orderId", required = false) Integer orderId,
//            @RequestParam(value = "type", required = false) Integer type,
//            @RequestParam(value = "inHand", required = false) Integer inHand,
//            @RequestParam(value = "reason", required = false) String reason,
//            @RequestParam(value = "status", required = false) Integer status,
//            @RequestParam(value = "explainn", required = false) String explainn,
//            @RequestParam(value = "receiver", required = false) String receiver,
//            @RequestParam(value = "address", required = false) String address,
//            @RequestParam(value = "phone", required = false) String phone,
//            @RequestParam(value = "logistics", required = false) String logistics,
//            @RequestParam(value = "courierNumber", required = false) String courierNumber,
//            @RequestParam(value = "senderPhone", required = false) String senderPhone,
//            @RequestParam(value = "refuseReason", required = false) String refuseReason
//    ) {
//        OrderRefund entity = new OrderRefund();
//        entity.setOrderRefundId(orderRefundId);
//        entity.setOrderId(orderId);
//        entity.setType(type);
//        entity.setInHand(inHand);
//        entity.setReason(reason);
//        entity.setStatus(status);
//        entity.setExplainn(explainn);
//        entity.setReceiver(receiver);
//        entity.setAddress(address);
//        entity.setPhone(phone);
//        entity.setLogistics(logistics);
//        entity.setCourierNumber(courierNumber);
//        entity.setSenderPhone(senderPhone);
//        entity.setRefuseReason(refuseReason);
//        orderRefundService.updateById(entity);
//        return ResultBodyUtils.ok();
//    }
//
//    /**
//     * 删除数据
//     * @param id 单个id
//     * @param ids 多个id用,号隔开
//     * @return
//     */
//    @PostMapping("remove")
//    public ResultBody remove(
//            @RequestParam(value = "id", required = false) Long id,
//            @RequestParam(value = "ids", required = false) String ids
//    ) {
//        if(id != null && id > 0) {
//            orderRefundService.removeById(id);
//        }
//        if(ids != null && ids.length() > 0) {
//            orderRefundService.removeByIds(Arrays.asList(ids.split(",")));
//        }
//        return ResultBodyUtils.ok();
//    }

}
